package org.iabako.server.tools;

import org.iabako.shared.entity.enumeration.Language;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Locale;

/**
 * Created by jose on 16/09/14.
 */

@Component
public class BundleMessages {

    @Autowired
    protected MessageSource resource;

    public String getLabel(String labelKey, String... args) {

        return getLabel(getLanguage(), labelKey, args);
    }

    public Language getLanguage() {
        HttpSession session = (((ServletRequestAttributes) RequestContextHolder.
                currentRequestAttributes()).getRequest()).getSession();

        Language language = (Language) session.getAttribute("IABAKO_LANG");

        if (language == null) {
            language = getLanguageFromCookie();
        }
        return language;
    }

    private Language getLanguageFromCookie() {
        String language = null;

        HttpServletRequest request = (((ServletRequestAttributes) RequestContextHolder.
                currentRequestAttributes()).getRequest());

        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("IABAKO_LANG".equals(cookie.getName())) {
                    language = cookie.getValue();
                }
            }
        }

        //default lang
        Language pickedLang = Language.EN;

        for (Language lang : Language.values()) {
            if (lang.getLangString().equalsIgnoreCase(language)) {
                pickedLang = lang;
            }
        }

        return pickedLang;
    }

    public String getLabel(Language language, String labelKey, String... args) {
        try {
            return resource.getMessage(labelKey, args, new Locale(language.getLangString()));
        } catch (NoSuchMessageException e) {
            return labelKey;
        }
    }
}
